var url_service = "http://124.222.147.63:9555";

var currentDate = getCurrentDate();
var sessionId = '';

$(function () {
    // 获取会话列表
    getSessions();
    // 获取用户列表
    getUserList();
    // input 框宽度自适应
    inputAutoHeight();
    // 实时接收数据
    realData();
    // 回车键发送消息事件
    enterEveter();
})

function getSessions() {
    var userId = getPV('userId');
    var xsessionHtml = '';
    $.ajax({
        type: 'GET',
        url: url_service + '/api/xchat/getsessionlist?userId=' + userId,
        dataType: 'json',
        async: false,
        success: function (res) {
            if (res.success) {
                for (let item of res.data) {
                    var itemHtml = getXsessionItemHtml(item);
                    xsessionHtml += itemHtml;
                }
                $("#xsessionDiv").html(xsessionHtml);
            }
        }
    })
}

function getXsessionItemHtml(item) {
    var html = "<div class=\"xsessionItem\" id='"+item.sessionId+"' onclick=\"getMessage('"+item.sessionId+"',false,'')\">\n" +
            "    <img src=\"./img/xchat/chat.png\" class=\"xsessionIcon\">\n" +
            "    <span class=\"xsessionName\">"+item.sessionName+"</span>\n" +
            "  </div>";
    return html;
}

function getUserList() {
    var xuserHtml = '';
    $.ajax({
        type: 'GET',
        url: url_service + '/api/xchat/getuserlist',
        dataType: 'json',
        async: false,
        success: function (res) {
            if (res.success) {
                for (let item of res.data) {
                    var itemHtml = getXuserItemHtml(item);
                    xuserHtml += itemHtml;
                }
                $("#xuserDiv").html(xuserHtml);
            }
        }
    })
}

function getXuserItemHtml(item) {
    var html = "  <div class=\"xuserItem\" id=\"xuserItem\">" +
            "    <img src=\""+item.cover+"\" class=\"xuserIcon\">" +
            "    <span class=\"xuserName\">"+item.userName+"</span>" +
            "  </div>";
    return html;
}

function realData() {
    window.setInterval(function(){
        getMessage(sessionId,true,currentDate);
    },4000);
}

function getMessage(sid,isReal,time) {
    // 是否切换会话
    if (!isReal){
        sessionId = sid;
        $("#"+sessionId).addClass('xsessionItem-checked').siblings().removeClass('xsessionItem-checked');
        $("#messageDiv").html("");
    }
    var userId = getPV('userId');
    var xchatHtml = $("#messageDiv").html();
    $.ajax({
        type: 'GET',
        url: url_service + '/api/xchat/list?pageSize=20&sessionId=' + sessionId + '&userId=' + userId + '&time=' + time,
        dataType: 'json',
        async: false,
        success: function (res) {
            if (res.success) {
                for (let item of res.data) {
                    var itemHtml = getXchatItemHtml(item, '');
                    xchatHtml += itemHtml;
                }
                $("#messageDiv").html(xchatHtml);
            }
            if (res.extra > 0){
                currentDate = getCurrentDate();
                inputAutoHeight();
            }
            if (res.extra !== 0){
                chatReturn();
            }
        }
    })
}

function getXchatItemHtml(item, newId) {
    var html;
    if (item.me) {
        html = "  <div class=\"xchatItem_right\">\n" +
            "    <input class=\"message rightItemBg\" id=\"" + newId + "\" type=\"textarea\" value=\"" + item.content + "\" />\n" +
            "    <img class=\"icon rightIcon\" src=\""+item.userCover+"\" />\n " +
            "  </div>";
    } else {
        html = "  <div class=\"xchatItem_left\">\n" +
            "    <img class=\"icon leftIcon\" src=\""+item.userCover+"\" />\n" +
            "    <input class=\"message\" id=\"" + newId + "\" type=\"textarea\" value=\"" + item.content + "\" />\n" +
            "  </div>";
    }
    return html;
}

function inputAutoHeight() {
    var list = document.getElementsByClassName('message');
    for (var i in list) {
        if (list[i]!=list.length)
            updateWidth(list[i]);
    }
}

function updateWidth(option) {
    var current_width = 40;
    for (let item of $(option).val()) {
        if (isChinese(item))
            current_width += 15;
        else
            current_width += 8;
    }
    $(option).css("width", current_width + "px");
}

function chatReturn() {
    var div = document.getElementById('messageDiv');
    div.scrollTop = div.scrollHeight;
}

// function send() {
//     if (sessionId === '' || sessionId === null || sessionId === undefined){
//         layer.open({
//             title: false
//             , content: " 请选择聊天会话再进行发消息好嘛？亲 "
//             , btn: ['好嘟']
//         });
//         return;
//     }
//     var userId = getPV('userId');
//     var messageValue = $("#messageValue").val();
//     if (messageValue === '' || messageValue === null || messageValue === undefined)
//         return;
//     $.ajax({
//         type: 'POST',
//         url: url_service + '/api/xchat/send?chatType=text&userId=' + userId + '&content=' + messageValue + '&sessionId=' + sessionId,
//         dataType: 'json',
//         async: false,
//         success: function (res) {
//             // if (res.success) {
//             //     updateMessage(res.data);
//             //     chatReturn();
//             // }
//         }
//     })
//     $("#messageValue").val("");
// }

function isChinese(temp) {
    var re = /[^\u4E00-\u9FA5]/;
    if (re.test(temp)) return false;
    return true;
}

function getPV(name) {
    var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
    var r = window.location.search.substr(1).match(reg);
    if (r != null) {
        return unescape(r[2]);
    }
    return null;
}

function getCurrentDate() {
    let time = new Date()
    let nowTime = DateSF(time.toLocaleString('en-US',{hour12: false}).split(" "));
    return nowTime;
}

function DateSF(times) {
    let time = times[1]
    let mdy = times[0]
    mdy = mdy.split('/')
    let month = parseInt(mdy[0]);
    let day = parseInt(mdy[1]);
    let year = parseInt(mdy[2])
    return year + '-' + ((month < 10) ? '0' + month : month) + '-'  + ((day < 10) ? '0' + day : day) + ' ' + time
}

function enterEveter(){
    document.onkeydown = function (e) {
        var keycode = document.all ? event.keyCode : e.which;
        if (keycode == 13) {
            send();
        }
    }
}

let websocket = null;
if ('WebSocket' in window) {
    websocket = new WebSocket("ws://http://localhost:9555/webSocket");
    console.log("SpringBoot Websocket 链接成功!")
} else {
    alert('浏览器不支持webSocket');
}

//连接发生错误的回调方法
websocket.onerror = function () {
    console.log("SpringBoot Websocket 链接失败!")
};

//连接成功建立的回调方法
websocket.onopen = function (event) {
    console.log("SpringBoot Websocket 链接成功!")
};


//连接关闭的回调方法
websocket.onclose = function () {
    console.log("SpringBoot Websocket 关闭链接!")
};

//关闭连接
function closeWebSocket() {
    websocket.close();
};

//发送消息
function send() {
    if (sessionId === '' || sessionId === null || sessionId === undefined){
        layer.open({
            title: false
            , content: " 请选择聊天会话再进行发消息好嘛？亲 "
            , btn: ['好嘟']
        });
        return;
    }
    var userId = getPV('userId');
    var messageValue = $("#messageValue").val();
    if (messageValue === '' || messageValue === null || messageValue === undefined)
        return;
    let xchatContet = {
        userId: userId,
        messageValue: messageValue,
        sessionId: sessionId
    }
    websocket.send(JSON.stringify(xchatContet));
    $("#messageValue").val("");
};

//接收到消息的回调方法
websocket.onmessage = function (event) {
    let data = event.data;
    console.log("后端传递的数据:" + data);
    $("#online").html(data);
};